﻿using InputKeyboard.View;
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace InputKeyboard
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            Kill();
            Current.MainWindow = CreateKeyboardWindow(AnalysisParam(e.Args));
            base.OnStartup(e);
            Current.MainWindow.ShowDialog();
        }
        /// <summary>
        /// 解析参数
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static WindowShowParam AnalysisParam(params string[] args)
        {
            WindowShowParam param = new WindowShowParam();
            if (args != null && args.Length > 0)
            {
                foreach (var arg in args)
                {
                    if (string.IsNullOrEmpty(arg)) continue;
                    var temps = arg.Split('=');
                    if (temps.Length != 2 || string.IsNullOrEmpty(temps[0]) || string.IsNullOrEmpty(temps[1])) continue;
                    switch (temps[0].ToLower())
                    {
                        case "layout":
                            param.Layout = temps[1];
                            break;
                        case "multitouch":
                            {
                                var p = temps[1].ToLower();
                                param.MultiTouch = "true".Equals(p) || "1".Equals(p);
                            }
                            break;
                        case "left":
                            {
                                var p = temps[1].ToLower();
                                if (double.TryParse(p, out double left)) param.Left = left;
                            }
                            break;
                        case "top":
                            {
                                var p = temps[1].ToLower();
                                if (double.TryParse(p, out double top)) param.Top = top;
                            }
                            break;
                        case "title":
                            param.Title = temps[1];
                            break;
                        case "opacity":
                            if (double.TryParse(temps[1], out double opacity)) param.Opacity = opacity;
                            break;
                        default:
                            break;
                    }
                }
            }
            return param;
        }

        /// <summary>
        /// 创建窗口
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static BaseWindow CreateKeyboardWindow(WindowShowParam param)
        {
            switch (param.Layout.ToLower())
            {
                case "number":
                    return new View.Number(param);
                case "numbersymbol":
                    return new View.NumberAndSymbol(param);
                case "letters":
                    return new View.Letters(param);
                case "lettersnumber":
                    return new View.LettersAndNumber(param);
                case "lettersnumbernofunctionkeys":
                    return new View.LettersAndNumberNoFunctionKeys(param);
                default:
                    return new View.Normal(param);
            }
        }

        private static BaseWindow ShowingWindow;
        /// <summary>
        /// 显示键盘窗口,程序引用dll方式时使用
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void ShowKeyboardWindow(WindowShowParam param)
        {
            if (ShowingWindow != null && ShowingWindow.IsVisible) ShowingWindow.Dispatcher.Invoke(() => { ShowingWindow.Close(); });
            var thread = new Thread(() =>
            {
                ShowingWindow = CreateKeyboardWindow(param);
                ShowingWindow.ShowDialog();
                ShowingWindow = null;
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
        }

        private void Kill()
        {
            try
            {
                var current = Process.GetCurrentProcess();
                var ps = Process.GetProcessesByName("InputKeyboard");
                foreach (var p in ps)
                {
                    if (p.Id == current.Id) continue;
                    p.Kill();
                }
            }
            catch (Exception)
            {

            }
        }
    }

    /// <summary>
    /// 启动参数
    /// </summary>
    public class WindowShowParam
    {
        /// <summary>
        /// 窗口布局
        /// </summary>
        public string Layout { get; set; } = "normal";
        /// <summary>
        /// 是否多点触控
        /// </summary>
        public bool MultiTouch { get; set; } = false;
        /// <summary>
        /// 窗口坐标左位置
        /// </summary>
        public double? Left { get; set; } = null;
        /// <summary>
        /// 窗口坐标上位置
        /// </summary>
        public double? Top { get; set; } = null;
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; } = null;
        /// <summary>
        /// 透明度
        /// </summary>
        public double Opacity { get; set; } = 1d;

        /// <summary>
        /// 线程调度，切换语言时使用
        /// </summary>
        public Dispatcher Dispatcher { get; set; }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("layout=");
            sb.Append(Layout);
            sb.Append(" multitouch=");
            sb.Append(MultiTouch);
            sb.Append(" opacity=");
            sb.Append(Opacity);
            if (Left.HasValue)
            {
                sb.Append(" left=");
                sb.Append(Left);
            }
            if (Top.HasValue)
            {
                sb.Append(" top=");
                sb.Append(Top);
            }
            if (!string.IsNullOrEmpty(Title))
            {
                sb.Append(" title=");
                sb.Append(Title);
            }
            return sb.ToString();
        }
    }


}
